//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2006
//
// Object element properties.
//

# include "StdAfx.h"
# include "EditElement.h"
# include "Map.h"
# include "MapView.h"
# include "EditPoint.h"
# include "EditText.h"
# include "MoveObject.h"
# include "SetElementPoints.h"
# include "PrintUnits.h"
# include "ParseHelpers.h"
# include "Wrappers.h"
# include "Globals.h"

static
bool ParsePoints (const string_t & _strPoints, points_t & _points) {
	const char * p = _strPoints.data ();
	const char * const pEnd = p + GetLineLen (p, p + _strPoints.size ());

	while (p < pEnd) {
		point_t point;

		OmitSpaces (& p, pEnd);
		if (! ParseArc (p, pEnd, & p, point.y))
			return false;

		OmitSpaces (& p, pEnd);
		if (! ParseArc (p, pEnd, & p, point.x))
			return false;

		_points.push_back (point);
	}

	return true;
}

bool EditElementPoints (HWND _hWnd, rgn_t * _pRgn, size_t _cElementOrOrigin) {
	if (_pRgn->Kind == rkPoint) {
		if (_cElementOrOrigin >= _pRgn->origins.size ())
			return false;
		rgn_origin_t & origin = _pRgn->origins [_cElementOrOrigin];

		point_t point = origin.point;
		if (! EditPoint (_hWnd, point))
			return false;

		MoveObject (_pRgn, _cElementOrOrigin, point_t (point.x - origin.point.x, point.y - origin.point.y));
	} else {
		assert (_pRgn->Kind == rkPolyline || _pRgn->Kind == rkPolygon);

		if (_cElementOrOrigin >= _pRgn->elements.size ())
			return false;
		rgn_element_t & element = _pRgn->elements [_cElementOrOrigin];

		points_t & points = element.points;
		const size_t cPoints = points.size ();

		// Prepare text.
		const size_t c_cMaxCharsPerPoint = 64;
		char * const strPoints = new char [cPoints*c_cMaxCharsPerPoint + 1];
		CArrayHolder<char> strPoints_Holder (strPoints);
		size_t cPos = 0;

		for (size_t cPoint = 0; cPoint < cPoints; ++ cPoint) {
			char * const strPoint = strPoints + cPos;
			PrintPosition (strPoint, points [cPoint]);
			const size_t cPointLen = ::strlen (strPoint);

			cPos += cPointLen;

			strPoints [cPos ++] = '\r';
			strPoints [cPos ++] = '\n';

			assert (cPos < cPoints*c_cMaxCharsPerPoint);
		}
		strPoints [cPos] = '\0';
		string_t strPoints2 (strPoints);

		// Edit text.
		points_t pointsNew;
		while (true) {
			if (! EditText (_hWnd, strPoints2, "Nodes", true))
				return false;

			pointsNew.clear ();
			if (ParsePoints (strPoints2, pointsNew))
				break;
			ErrorMsgBox ("Incorrect data.");
		}

		SetElementPoints (_pRgn, _cElementOrOrigin, pointsNew, point_extras_t ());

		Refresh ();
	}

	return true;
}